﻿/* 功能:  个人商户订单管理
 * 创建人：Kencery  创建时间：2018-2-3
 */
var ml = window.ml || {};
ml.admin = ml.admin || {};

ml.admin.orderindex = (function () {
    var defaults = {
        listUrl: "/Order/ListUser",
        getOrderStateUrl: "/Common/GetOrderState",
        stateUrl: "/Order/UpdateState",
        detailUrl: "/Order/GetDetailById"
    };
    var opt = {};

    var columns = [{
        field: 'state',
        radio: true
    }, {
        title: '行号',
        field: 'number',
        align: 'center',
        hide: true,
        formatter: plscommon.tableNumber
    }, {
        title: '订单ID',
        field: 'Id',
    }, {
        title: '用户名/流水号',
        field: 'NickName',
        align: 'center',
        formatter: function (value, rows, index) {
            return rows.NickName + "</br>" + rows.OrderNumber;
        }
    }, {
        title: '总价',
        field: 'Price',
        align: 'center',
    }, {
        title: '优惠价',
        field: 'DiscountPrice',
        align: 'center',
    }, {
        title: '实付价',
        field: 'ActPayPrice',
        align: 'center',
    }, {
        title: '人民币',
        field: 'ActPayRMB',
        align: 'center',
    }, {
        title: '订单/支付状态',
        field: 'State',
        align: 'center',
        formatter: function (value, rows, index) {
            var payState = returnPayStatue(rows.PayState);
            var state_html = "<p class='state_info' state='" + rows.State + "'>" + rows.StateName + "</p>";
            return state_html + payState;
        }
    }, {
        title: '下单时间',
        field: 'CreateTime',
        align: 'center',
    }, {
        title: '订单备注',
        field: 'Description',
        align: 'center',
    }, {
        title: '用餐人数',
        field: 'NumberOfMeals',
        align: 'center',
    }];

    var initTable = function () {
        plscommon.bootstraptable({
            id: "#orderinfo",
            url: defaults.listUrl,
            queryParams: queryParams,
            uniqueId: "Id",
            columns: columns
        });
    }

    var queryParams = function (params) {
        return {
            offset: params.offset,             //后台计算显示数据信息
            pagesize: params.limit,            //每页显示多少行
            merchantname_search: $("#merchantname_search").val(),
            ordernumber_search: $("#ordernumber_search").val(),
            state_search: $("#state_search").val(),
            paystate_search: $("#paystate_search").val()
        };
    };

    var initDropDownList = function () {
        plscommon.dropDownList("#state_search", defaults.getOrderStateUrl, 1, 1);

        //初始化定时器并且每隔1分钟判断一下是否含有未接单的订单，如果有，调用语音播报
        setInterval(InterValReport, 1000 * 60);
    }

    var InterValReport = function () {
        var state = [];
        $(".state_info").each(function () {
            state.push($(this).attr("state"));
        });

        var index = $.inArray('0', state);
        if (index != -1) {
            //监控到有新的订单语音提示
            var myAuto = document.getElementById('audionew');
            myAuto.play();
        }
        plscommon.refreshTable("orderinfo");
    }

    var clickEvent = function () {
        $("#btnQueryList").on("click", function () { btnQueryList(); });                 //按条件查询结果
        $("#btnReset").on("click", function () { btnReset(); });                         //清空文本框信息

        $("#btnReceivingDialog").on("click", function () { btnReceivingDialog(); });     //接单
        $("#btnCancelDialog").on("click", function () { btnCancelDialog(); });           //取消订单
        $("#btnStateOK").on("click", function () { btnStateOK(); });                     //接单取消订单方法

        $("#btnDetailDialog").on("click", function () { btnDetailDialog(); });           //订单详情
    };

    var btnQueryList = function () {
        plscommon.refreshTable("orderinfo");
    }

    var btnReset = function () {
        plscommon.resetFrom("formSearch");
    }

    var btnReceivingDialog = function () {
        //必须选择数据并且当前的状态为待处理才能够接单，否则不允许接单
        var data = plscommon.dialogWaringDisable('orderinfo', 'StateOperation');
        if (!data) {
            return false;
        }
        if (data.State != 0) {
            plscommon.warningMessage("该订单已经处理过了，不允许接单", 3000);
            return false;
        }
        if (data.PayState == 0) {
            plscommon.warningMessage("该订单还未支付，不允许接单", 3000);
            return false;
        }

        $("#StateModal").modal();
        $("#stateInfo").hide();
        $("#state_id").val(data.Id);
        $("#State_Head_Title").text("（" + data.OrderNumber + "）接单");
        $("#State_Head_Title_OK").text("接订单（" + data.OrderNumber + "）");
        opt.state = 1;  // 1:接单
    }

    var btnCancelDialog = function () {
        //必须选择数据并且当前的状态为待处理才能够接单，否则不允许接单
        var data = plscommon.dialogWaringDisable('orderinfo', 'StateOperation');
        if (!data) {
            return false;
        }
        if (data.State == 3) {
            plscommon.warningMessage("该订单已经完成，不允许取消", 3000);
            return false;
        }
        if (data.State == 4 || data.State == 5 || data.State == 6) {
            plscommon.warningMessage("该订单已经取消过了，不允许再次取消", 3000);
            return false;
        }

        $("#StateModal").modal();
        if (data.PayState == 0) {
            $("#stateInfo").hide();
        } else {
            $("#stateInfo").show();
        }

        $("#state_id").val(data.Id);
        $("#State_Head_Title").text("（" + data.OrderNumber + "）取消");
        $("#State_Head_Title_OK").text("取消订单（" + data.OrderNumber + "）");
        opt.state = 2;  // 2:取消
    }

    var btnStateOK = function () {
        var state_id = $("#state_id").val();
        if (!state_id) {
            plscommon.warningMessage("请您选择需要操作的数据", 4000);
            return false;
        }

        $("#btnStateOK").prop("disabled", true);
        plscommon.ajax({
            disableId: "btnStateOK",
            url: defaults.stateUrl,
            type: "POST",
            data: { Id: state_id, State: opt.state },
            success: function () {
                $('#StateModal').modal('hide');
                $("#orderinfo").bootstrapTable('refresh');
            }
        });
    }

    var btnDetailDialog = function () {
        //必须选中一条才能弹出
        var data = plscommon.dialogWaring('orderinfo', 'DetailModal', 'orderDetail');
        if (!data.Id) {
            return false;
        }

        plscommon.ajax({
            url: defaults.detailUrl,
            type: "GET",
            data: { id: data.Id },
            success: function () {
                var data = this.data;
                $("#detail_orderumber").val(data.OrderNumber);
                $("#detail_nickname").val(data.NickName);
                $("#detail_merchant_name").val(data.Name);
                $("#detail_price").val(data.Price);
                $("#detail_discountprice").val(data.DiscountPrice);
                $("#detail_actpayprice").val(data.ActPayPrice);
                $("#detail_actpay_rmb").val(data.ActPayRMB);

                if (!data.ContactName) {
                    $("#detail_address").val("");
                } else {
                    $("#detail_address").val("收货人名称：" + data.ContactName + "，收货人电话：" + data.Contact + "，收货人地址：" + data.Address);
                }
                $("#detail_paymethod").val(data.PayMethod);
                $("#detail_numberofmeals").val(data.NumberOfMeals);
                $("#detail_redpackagetype").val(data.RedPackageType);
                $("#detail_description").val(data.Description);
                $("#detail_state").val(data.StateName);
                $("#detail_paystate").val(returnPayStatue(data.PayState));
                $("#detail_createtime").val(data.CreateTime);
                $("#detail_servicetime").val(data.ServiceTime);
                $("#detail_numberOfMeals").val(data.NumberOfMeals);

                $('#tbody').empty();
                if (data.orderDetail != null) {
                    var html = "";
                    for (var i = 0; i < data.orderDetail.length; i++) {
                        var result = data.orderDetail[i];
                        html += '<tr><td>' + result.Name + '</td><td>' + result.ProductNumber + '</td><td>' + result.ProductPrice + '</td></tr>';
                    }
                    $('#tbody').append(html);
                }
            }
        });
    }

    var returnPayStatue = function (value) {
        var result = "";
        if (value == 0) {
            result = "未支付";
        }
        if (value == 1) {
            result = "已支付";
        }
        return result;
    }

    return {
        init: function (options) {
            $.extend(defaults, options || {});
            initTable();            //初始化Table表格
            clickEvent();           //触发事件
            initDropDownList();     //初始化下拉事件
        }
    };
}());